package com.experient.test;

import android.accounts.NetworkErrorException;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.dmcbig.mediapicker.utils.ScreenUtils;
import com.experient.test.api.GetTableList;
import com.experient.test.struct.Table;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static android.content.Context.MODE_PRIVATE;

/**
 * Implementation of App Widget functionality.
 */
public class ClassTableWidgetProvider extends AppWidgetProvider {


    /**
     * 当有数据更新时调用
     */

    private static final String UPDATE_ACTION = "TABLE_UPDATE_ACTION";
    private static String SafeCode;


    /**
     * 收到广播后会自动调用onReceive方法
     * @param context 上下文
     * @param intent 意图
     */
    @SuppressLint("Range")
    @Override
    public void onReceive(Context context, Intent intent){
        super.onReceive(context, intent);

        //动态注册广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(UPDATE_ACTION);
        context.getApplicationContext().registerReceiver(this,filter);

        Log.d("收到广播","收到广播"+intent.getAction());

        SQLiteDatabase db = context.openOrCreateDatabase("DCStorage", MODE_PRIVATE, null);;

        Cursor cursor = db.query("DC_1908175602_storage", null, "key=?", new String[]{"SafeCode"}, null, null, null);


        if (cursor.moveToFirst()) {
            SafeCode = cursor.getString(cursor.getColumnIndex("value"));
            cursor.close();
        }

        db.close();

        //创建线程池来获取课程表数据
        ThreadFactory threadFactory = Thread::new;
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), threadFactory);
        threadPoolExecutor.execute(() -> {
            try {

                Map tableList = GetTableList.getTableData(SafeCode);

                List<Map> tableList1 = (List<Map>) tableList.get("classTable");

                List<Table> tableList2 = new ArrayList<>();

                for (Map map : tableList1) {
                    Table table = new Table();
                    table.setClassName((String) map.get("subject"));
                    table.setRoomName((String) map.get("classroom"));
                    table.setTeacherName((String) map.get("teacher"));
                    table.setSection((String) map.get("section"));
                    table.setFromTime((String) map.get("fromTime"));
                    table.setToTime((String) map.get("toTime"));

                    tableList2.add(table);
                }

                String week = (String) tableList.get("week");
                String day = (String) tableList.get("day");

                //更新数据
                TableRemoteViewFactory.refresh(tableList2);

                //更新界面
                RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.my_widget);
                remoteViews.setTextViewText(R.id.weekData, "第"+week+"周 / "+day);


                //通知刷新页面
                AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
                ComponentName componentName = new ComponentName(context, ClassTableWidgetProvider.class);
                appWidgetManager.updateAppWidget(componentName, remoteViews);
                appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetManager.getAppWidgetIds(componentName), R.id.tableList);

            } catch (NetworkErrorException | JSONException e) {
                e.printStackTrace();
            }
        });



//        }

    }


    /**
     * 在每次新增一个widget时调用
     * @param context 上下文
     * @param appWidgetManager 小部件的管理器
     * @param appWidgetIds 小部件的id
     */
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

        //动态注册广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(UPDATE_ACTION);
        context.getApplicationContext().registerReceiver(this,filter);

        Log.d("注册成功","注册成功");

        //对于每一个小部件，都创建一个RemoteViews对象
        for (int appWidgetId : appWidgetIds) {

            //获取小部件的布局
            RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.my_widget);
            
            //设置数据列表的适配器
            Intent serviceIntent = new Intent(context,ClassTableService.class);
            serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,appWidgetId);
            remoteViews.setRemoteAdapter(R.id.tableList,serviceIntent);

            //设置点击事件
            Intent clickIntent = new Intent().setAction(UPDATE_ACTION);
            //todo:设置为只允许当前软件接受广播
            clickIntent.setPackage(context.getPackageName());
            clickIntent.setComponent(new ComponentName(context,ClassTableWidgetProvider.class));

            @SuppressLint("UnspecifiedImmutableFlag") PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0,clickIntent,PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.refresh, pendingIntent);

            appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.tableList);
            appWidgetManager.updateAppWidget(appWidgetId,remoteViews);

        }
        super.onUpdate(context,appWidgetManager,appWidgetIds);
    }

    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
    }

    @Override
    public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {
        super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
    }

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
    }

    @Override
    public void onDisabled(Context context) {
        super.onDisabled(context);
    }
}